<template>
  <div class="top-up">
    <el-card>
      <el-card header="充值">
        <el-form class="service-info" label-width="120px">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-tooltip class="item" effect="dark" content="单次充值金额不能超过5位数哦~" placement="top-start">
                <el-form-item label="充值金额" prop="county">
                  <el-input v-model="topUpForm.amount" type="text" maxlength="5" minlength="3" placeholder="充值金额"
                            clearable/>
                </el-form-item>
              </el-tooltip>
            </el-col>
            <el-col :span="6">
              <m-button text="立即充值" @click="topUp()"
                        :classStyle="topUpForm.amount>0?'main-btn':'disabled-btn'"></m-button>
            </el-col>
            <el-col :span="6">
              账户余额: <span style="font-weight: bold;color: red">{{ Number(userInfo.amount).toFixed(2) }}</span>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <el-card v-show="payObj.orderId&&payObj.payUrl" class="ub main-center">
        <el-card>
          <div>
            <img style="height: 34px" :src="payImg" alt="">
          </div>
        </el-card>
        <div style="text-align:center">
          <div>
            <canvas id="qrcode" style="height: 220px;width: 220px"></canvas>
          </div>
          <div style="font-weight: bolder;font-size: small">请使用支付宝扫码</div>
          <span style="font-weight: bolder;font-size:6px">总金额: <span style="color: red;">
            {{ payObj.amount }}</span> 元</span>
        </div>
      </el-card>
    </el-card>
    <el-empty v-if="topUpFlag" description="充值成功喽 , 去购物车看看~">
      <slot>
        <m-button text="去购物车" @click="toCart()" classStyle="main-btn"></m-button>
      </slot>
    </el-empty>
  </div>
</template>

<script>
import { ElMessageBox, ElNotification } from 'element-plus'
import memberApi from '../../api/member'
import topUpApi from '../../api/topUp'
import { onMounted, reactive, ref, toRefs, watch } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
// 引入生成二维码的组件
import QRCode from 'qrcode'
import MButton from '../../components/MButton.vue'
export default {
  name: 'TopUp',
  components: {
    MButton,
    QRCode
  },
  setup () {
    const store = useStore()
    const router = useRouter()
    const state = reactive({
      // 充值信息
      topUpForm: {},
      // 支付对象
      payObj: {},
      // 支付成功标识
      topUpFlag: false,
      // 定时轮询对象
      intervalObj: undefined,
      payImg: 'https://linq-cool.oss-cn-shanghai.aliyuncs.com/20210214/b0a09d5634ff4d3fa2c6549adfc9b8f8.png'
    })
    let userInfo = store.getters.userInfo
    //----------------------方法 start
    const useqrcode = (qrcodeUrl) => {
      let qrcode = document.getElementById('qrcode')
      console.dir(qrcode)
      QRCode.toCanvas(qrcode, qrcodeUrl, function (error) {
        if (error) console.error(error)
        console.log('QRCode success!')
      })
    }
    // 更新用户信息
    const updateUserInfo = async () => {
      await store.dispatch('GetInfo')
    }
    // 充值金额
    const topUp = () => {
      state.topUpFlag = false
      let reExp = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/
      if (reExp.test(state.topUpForm.amount)) {
        ElMessageBox.confirm(`确定要充值【${state.topUpForm.amount}】元么~`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          setTimeout(() => {
            ElMessageBox.confirm('是否确定创建订单并使用支付宝支付?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              memberApi.topUpWithAlipay(userInfo.id, state.topUpForm.amount).then(res => {
                state.payObj = res.data
                // 创建二维码
                useqrcode(res.data.payUrl)
                console.log('qrcode:', state.qrcode)
                ElNotification.success('订单创建成功，请扫码支付')
                state.intervalObj = setInterval(() => {
                  topUpApi.getTopUp(state.payObj.orderId).then(r => {
                    if (r.data.status === 1) {// 说明订单状态为支付成功
                      // 清空定时器
                      clearInterval(state.intervalObj)
                      ElNotification.success('支付成功')
                      state.topUpFlag = true
                      // 更新用户状态
                      updateUserInfo()
                      state.payObj = {}
                    }
                  }).catch(() => {
                    // 清空定时器
                    clearInterval(state.intervalObj)
                  })
                }, 2000)
              })
            }).catch(() => {
              ElNotification.error('支付失败')
            }).catch(() => {
              ElNotification.warning('支付取消')
            })
          }, 500)
        }).catch(error => {
          ElNotification.warning('正在取消充值...')
        })
      } else {
        ElNotification.warning('充值金额不合法哦~')
      }

    }
    // 如果用户没有支付，而弹出层被关闭了
    const handleClose = () => {
      ElMessageBox.confirm('您确定放弃支付吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        ElNotification.warning('您已放弃支付，可以回到充值记录查询列表里面再次支付')
        clearInterval(state.intervalObj)
      }).catch(() => {
        ElNotification.success('欢迎继续支付')
      })
    }

    // 去购物
    const toCart = () => {
      router.push('/cart')
    }
    //----------------------方法 end


    //----------------------watch监听  start
    //----------------------watch监听 end

    //--------------- onMouted start
    onMounted(() => {

    })


    //--------------- onMouted end


    return {
      toCart,
      handleClose,
      topUp,
      userInfo,
      ...toRefs(state)
    }
  }
}
</script>

<style scoped lang="scss">
.top-up {
  margin-top: 20px;
}


</style>
